//
//  AppDelegate.m
//  jinnengExam
//
//  Created by mac on 2020/8/8.
//  Copyright © 2020 jznrj. All rights reserved.
//

#import "AppDelegate.h"
#import "TabViewController.h"
#import "LoginViewController.h"
#import "JZNRequestUtil.h"
#import "URLUtil.h"
#import <MJExtension.h>
#import <MJExtension/NSObject+MJKeyValue.h>
#import "MateAppriseViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [self VersonUpdate];
    
    TabViewController *tb = [[TabViewController alloc]init];
    tb.selectedIndex = 2;
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = tb;
    [self.window makeKeyAndVisible];
//    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
//    if ([userDefault objectForKey:@"account"] != nil) {
//        [self relogin];
//    }else{
//        self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
//        self.window.backgroundColor = [UIColor whiteColor];
//        LoginViewController *login = [[LoginViewController alloc]init];
//        //login.navigationBar.hidden = YES;
//        self.window.rootViewController = login;
//        [self.window makeKeyAndVisible];
//    }
    
    return YES;
}


#pragma mark - UISceneSession lifecycle


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [self VersonUpdate];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(void)VersonUpdate{
 
  //定义app地址
  NSString *urld = [NSString  stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%d",1526462237];
 
  NSURL *url = [NSURL URLWithString:urld];
 
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
 
  [request setHTTPMethod:@"POST"];
 
  NSURLSession *session = [NSURLSession sharedSession];
 
  NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
 
    NSLog(@"%@",response);
 
    NSMutableDictionary *receiveStatusDic = [[NSMutableDictionary alloc]init];
 
    if (data) {
 
      NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
      if ([[receiveDic valueForKey:@"resultCount"] intValue] > 0) {
 
        [receiveStatusDic setObject:@"1" forKey:@"status"];
 
        [receiveStatusDic setObject:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]  forKey:@"version"];
 
        [self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO];
 
      }else{
 
        [receiveStatusDic setValue:@"1" forKey:@"status"];
 
      }
    }else{
 
      [receiveStatusDic setValue:@"-1" forKey:@"status"];
    }
 
  }];
 
  [task resume];
 
}

-(void)receiveData:(id)sender
{
  //获取APP自身版本号
  NSString *localVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];
 
  NSArray *localArray = [localVersion componentsSeparatedByString:@"."];//1.0
  NSArray *versionArray = [sender[@"version"] componentsSeparatedByString:@"."];//3 2.1.1
 
//  if ((versionArray.count == 2) && (localArray.count == versionArray.count)) {
 
    if ([localArray[0] intValue] < [versionArray[0] intValue]) {
 
      [self updateVersion];
 
    }else if ([localArray[0] intValue] == [versionArray[0] intValue]){
      if ([localArray[1] intValue] < [versionArray[1] intValue]) {
        [self updateVersion];
 
      }else if ([localArray[1] intValue] == [versionArray[1] intValue]){
        if ([localArray[2] intValue] < [versionArray[2] intValue]) {
 
          [self updateVersion];
 
        }
      }
    }
//  }
 
}
 
-(void)updateVersion{
 
  NSString *msg = [NSString stringWithFormat:@"版本过低，需要升级到最新版本"];
  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"升级提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
  UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"现在升级" style:UIAlertActionStyleDestructive handler:^(UIAlertAction*action) {
 
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/app/m-help/id1526462237?mt=8"]];
    [[UIApplication sharedApplication]openURL:url];
  }];
  [alertController addAction:otherAction];
  [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
 
}
-(void) relogin{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *url = [NSString stringWithFormat:@"%@/user/userLogin" ,[URLUtil hostName]];
    NSDictionary *params = @{@"userMobile":[userDefault objectForKey: @"account"],
                             @"password":[userDefault objectForKey: @"pwd"],
                             @"businessCompanyId":@"1"
                             };
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        if(dataResult.code == 0){
            
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
             [userDefault setObject:dataResult.token forKey:@"token"];
             [userDefault setObject:[dataResult.data mj_JSONString] forKey:@"userInfo"];
            
            TabViewController *tb = [[TabViewController alloc]init];
            self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
            self.window.backgroundColor = [UIColor whiteColor];
            self.window.rootViewController = tb;
            [self.window makeKeyAndVisible];
        }else {
            [userDefault setObject:nil forKey:@"account"];
           [UIApplication sharedApplication].delegate.window.rootViewController = LoginViewController.new;
        }
    } failure:^(NSError *error) {
        
    }];
}

@end
